﻿/*
Prog : Excdom（Random Number Generator）
By lzexmpoane

项目始建于 2021 年 9 月 4 日 21 : 43 : 56

*/

#include"excdom.h"
#include"definition.h"
#include"audioclip.h"

void Excdom::InitRNG() {
    NumberDisSetText("inf", "INF");
    this->CountDownTimer = new QTimer(this);
    this->CountDownTimer->setTimerType(Qt::PreciseTimer);
    this->CountDownTimer->setInterval(25);
    connect(this->CountDownTimer, SIGNAL(timeout()), this, SLOT(TimeCountDown()));
    this->CountDownTimer->start();
    this->setWindowTitle(QString::fromStdString(ProgTitle));
    RunningNumberPosition = 0;
    on_RefreshListBut_clicked();
    setMinimumSize(1161, 226);
    setMaximumSize(1161, 226);
    setMaximumSize(1161, 600);
    on_actionMT19937_triggered();
    statusSum = new QLabel(this);
    statusDone = new QLabel(this);
    statusInfor = new QLabel(this);
    statusBar()->addWidget(statusSum);
    statusBar()->addWidget(statusDone);
    statusBar()->addPermanentWidget(statusInfor);
    statusSum->setText("  共计：NaN ");
    statusDone->setText(" 已抽：NaN ");
    statusInfor->setText(QString::fromStdString(ProgName + " " + Version + " - " + ProgBit + "位") + " By lzexmpoane | awa ");
}

Excdom::Excdom(QWidget *parent) : QMainWindow(parent) {
    ui.setupUi(this);
    InitRNG();
}

void Excdom::NumberDisSetText(const std::string &type, const QString &text) {
    if (type == "name") ui.NumberDis->setText("<p align = \"center\" style = \"color : " + NameColor + "\">" + text + "</p>");
    if (type == "inf") ui.NumberDis->setText("<p align = \"center\" style = \"color : " + InfColor + "\">" + text + "</p>");
    if (type == "end") ui.NumberDis->setText("<p align = \"center\" style = \"color : " + EndColor + "\">" + text + "</p>");
}

void Excdom::TimeCountDown() {
    if (!isMakingRandomNumber) {
        QDateTime time1 = QDateTime::fromString("2023-06-24 08:30:00", "yyyy-MM-dd hh:mm:ss");
        QDateTime time2 = QDateTime::currentDateTime();
        ll dt = time2.secsTo(time1);
        QString CntInfo = "<p align = \"center\" style = \"color : " + InfColor + "\">距中考剩 <span style = \"color : red\">" +
            QString::fromStdString(std::to_string(dt / 60 / 60 / 24)) + "天</span> " +
            QString::fromStdString(std::to_string(dt / 60 / 60 % 24)) + "时" +
            QString::fromStdString(std::to_string(dt / 60 % 60)) + "分" +
            QString::fromStdString(std::to_string(dt % 60)) + "秒</p>";
        ui.NumberDis->setText(CntInfo);
        ui.NumberDis->repaint();
    }
    else {
        if (namesScroll) {
            NumberDisSetText("name", QString::fromStdString(disFiles.result[rng.makeRange(RunningNumberPosition, disFiles.result.size() - 1)].name));
            ui.NumberDis->repaint();
        }
    }
}

void Excdom::ResetNumber() {
    NumberDisSetText("inf", "INF");
    RunningNumberPosition = RunningNumberSum = 0;
    if(rng.method == 1) UnfairRandomAlgorithm(disFiles.result);
    else PRandomAlgorithm(disFiles.result);
    ui.MakeButton->setEnabled(true);
    ui.MakeButton->setText("生成");
    if(rmSame == true) statusSum->setText("  共计：" + QString::fromStdString(std::to_string(disFiles.result.size())) + " ");
    else statusSum->setText("  共计：INF ");
    statusDone->setText(" 已抽：0 ");
}

void Excdom::MakeNumber() {
    if (rmSame == false) {
        RunningNumberPosition = 0;
        NumberDisSetText("name", QString::fromStdString(disFiles.result[rng.makeRange(RunningNumberPosition, disFiles.result.size() - 1)].name));
        ui.NumberDis->repaint();
        return;
    }
    if (RunningNumberPosition >= disFiles.result.size()) {
        NumberDisSetText("end", "抽完了 \\awa/");
        return;
    }
    NumberDisSetText("name", QString::fromStdString(disFiles.result[RunningNumberPosition].name));
    disFiles.result[RunningNumberPosition].count++;
    RunningNumberPosition++;
    RunningNumberSum++;
    statusDone->setText(" 已抽：" + QString::fromStdString(std::to_string(RunningNumberSum)) + " ");
}

void Excdom::on_MakeNumber_clicked() {
    isMakingRandomNumber = true;
    if(!namesScroll) {
        if (RunningNumberPosition >= disFiles.result.size()) {
            MakeNumber();
            return;
        }
        namesScroll = true;
        ui.MakeButton->setText(" 停止 ");
        QFont tmpfont = ui.MakeButton->font();
        tmpfont.setUnderline(true);
        ui.MakeButton->setFont(tmpfont);
        bool flag = false;
        ui.ResetButton->setEnabled(flag);
        ui.NameListCom->setEnabled(flag);
        ui.ReadListBut->setEnabled(flag);
        ui.checkRmSame->setEnabled(flag);
        ui.actionAlgorforList->setEnabled(flag);
        ui.actionSqMethod->setEnabled(flag);
        ui.actionLinMod->setEnabled(flag);
        ui.actionMT19937->setEnabled(flag);
        ui.IsRunningSounds->setEnabled(flag);
    }
    else {
        namesScroll = false;
        ui.MakeButton->setText("生成");
        QFont tmpfont = ui.MakeButton->font();
        tmpfont.setUnderline(false);
        ui.MakeButton->setFont(tmpfont);
        bool flag = true;
        ui.ResetButton->setEnabled(flag);
        ui.NameListCom->setEnabled(flag);
        ui.ReadListBut->setEnabled(flag);
        ui.checkRmSame->setEnabled(flag);
        ui.actionAlgorforList->setEnabled(flag);
        // ui.actionSqMethod->setEnabled(flag);
        ui.actionLinMod->setEnabled(flag);
        ui.actionMT19937->setEnabled(flag);
        // ui.IsRunningSounds->setEnabled(flag);
        MakeNumber();
    }
}

void Excdom::on_ResetNumber_clicked() {
    isMakingRandomNumber = false;
    ResetNumber();
}

void Excdom::on_QuitAct_triggered() {
    qApp->quit();
}

void Excdom::on_RefreshListBut_clicked() {
    ui.NameListCom->clear();
    ui.NameListCom->addItem("未选择");
    QDir *dirOfCntList = new QDir(QString::fromStdString(nameListPath));
    QStringList filterCntList;
    filterCntList << "*.txt";
    dirOfCntList->setNameFilters(filterCntList);
    QStringList CntListIndexItems = dirOfCntList->entryList();
    ui.NameListCom->addItems(CntListIndexItems);
    ui.ResetButton->setEnabled(false);
}

void Excdom::on_NameListCom_IndexChanged(const int &argv) {
    ui.MakeButton->setEnabled(false);
    ui.MakeButton->setText("请重置");
    ui.NameListView->clear();
    fileIncluded(ui.NameListCom->currentText().toStdString());
    if (argv == 0) {
        ui.ResetButton->setEnabled(false);
        ui.ResetButton->setText("请选择\n文件");
    }
    else {
        ui.ResetButton->setEnabled(true);
        ui.ResetButton->setText("重置");
    }
}

void Excdom::fileIncluded(const std::string &currentFileName) {
    std::string FileName = CntListPath;
    FileName += currentFileName;
    FileName = getThisPathInDir(FileName);
    if (isFileExist(FileName) == false) {
        QFile *WrtFile;
        WrtFile = new QFile;
        WrtFile->setFileName(QString::fromStdString(FileName));
        if (WrtFile->open(QIODevice::WriteOnly | QIODevice::Text)) {
            WrtFile->resize(0);
            std::string save;
            ReadFile(getThisPathInDir(nameListPath + currentFileName), save);
            std::vector<std::string> result;
            ll sum = 0, pos = 0;
            for (ll i = 0; i < save.length(); i++) {
                bool flag = false;
                while (isNumber(save[i])) {
                    flag = true;
                    sum = sum * 10 + save[i] - '0';
                    i++;
                }
                if (flag) {
                    pos = i;
                    break;
                }
            }
            pos++;
            qDebug("%d", pos);
            for (ll i = 1; i <= sum; i++) {
                std::string tmp = "";
                while (save[pos] != '\n' && save[pos] != '\0' && save[pos] != EOF) {
                    tmp += save[pos];
                    pos++;
                    if (pos >= save.length()) break;
                }
                result.push_back(tmp);
                pos++;
                if (pos >= save.length()) break;
            }
            QString file_w = "sum=" + QString::fromStdString(std::to_string(sum)) + ";\n";
            for (ll i = 1; i <= result.size(); i++) {
                file_w += QString::fromStdString(result[i - 1]) + "|0;\n";
            }
            WrtFile->write(file_w.toUtf8());
            WrtFile->close();
        }
    }
    if (disFiles.analyze(FileName)) {
        ui.NameListView->clear();
        UnfairRandomAlgorithm(disFiles.result);
        for (ll i = 0; i < disFiles.result.size(); i++) {
            ui.NameListView->addItem(QString::fromStdString(disFiles.result[i].name));
        }
    }
}

void Excdom::on_CmpFileHash_triggered() {
}

void Excdom::closeEvent(QCloseEvent *event) {
    // event->ignore();
    std::string FileName = CntListPath;
    FileName += ui.NameListCom->currentText().toStdString();
    disFiles.write(getThisPathInDir(FileName));
}

void Excdom::on_actionAlgorforList_triggered() {
    rng.method = 1;
    changedAlgor(rng.method);
}

void Excdom::on_actionSqMethod_triggered() {
    rng.method = 2;
    changedAlgor(rng.method);
}
void Excdom::on_actionLinMod_triggered() {
    rng.method = 3;
    changedAlgor(rng.method);
}
void Excdom::on_actionMT19937_triggered() {
    rng.method = 4;
    changedAlgor(rng.method);
}

void Excdom::changedAlgor(int method) {
    QString str = "「随机」算法：";
    QString names[] = { "", "《公平》的随机", "平方中值法", "线性同余法", "MT19937" };
    ui.labelAlgor->setText(str + names[method] + " ");
}

void Excdom::on_checkRmSame_clicked(bool checked) {
    rmSame = checked;
}

#include"about.h"

void Excdom::on_AboutExd_triggered(bool flag) {
    About* window_about = new About(this);
    window_about->ShowtheWindow();
}